#region License
///License Begin
///This program has been developed by: Rodolfo Grave de Peralta, 
///Copyright (C) 2007 Rodolfo Grave de Peralta
///This program is free software; you can redistribute it and/or modify
///it under the terms of the GNU General Public License as published by
///the Free Software Foundation; either version 2 of the License, or
///(at your option) any later version.
///
///This program is distributed in the hope that it will be useful,
///but WITHOUT ANY WARRANTY; without even the implied warranty of
///MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
///GNU General Public License for more details.
///
///You should have received a copy of the GNU General Public License
///along with this program; if not, write to the Free Software
///Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
///License End
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;

using System.Runtime.InteropServices;

using TEAM.TimeTracking.Model;

namespace TEAM.TimeTracking.View
{
    /// <summary>
    /// Interaction logic for FullWindow.xaml
    /// </summary>

    public partial class ReportWindow : System.Windows.Window
    {

        public const string TimeTemplate = "{0}:{1}";

        protected ICollectionView currentTaskExecutionsView;

        public ReportWindow()
        {
            InitializeComponent();
            currentTaskExecutionsView = CollectionViewSource.GetDefaultView(App.CurrentApp.CurrentModel.CurrentUser.History);
            try
            {
                //currentTaskExecutionsView.SortDescriptions.Add(new SortDescription("StartTime", ListSortDirection.Ascending));
            }
            catch (Exception ex)
            {
                MessageBox.Show("The entries could not be sorted by StartTime. Everything should continue to work ok.");
            }
            ctrlReports.SelectedValue = null;
        }

        public Report CurrentReport
        {
            get
            {
                return ctrlReports.SelectedValue as Report;
            }
            set
            {
                ctrlReports.SelectedValue = value;
            }
        }

        protected void UpdateReport_Click(object sender, RoutedEventArgs e)
        {
            UpdateReport();
        }

        protected void ExportToExcel_Click(object sender, RoutedEventArgs e)
        {
            ExportToExcel();
        }

        protected void TaskExecutionDelete_Click(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;
            if (b != null)
            {
                TaskExecution t = ((FrameworkElement)b.Parent).DataContext as TaskExecution;
                if (t != null)
                {
                    User currentUser = App.CurrentApp.CurrentModel.CurrentUser;
                    currentUser.RemoveTaskExecution(t);
                    App.CurrentApp.Database.Delete(t);
                    UpdateReport();
                }
            }
        }

        protected void ctrlReports_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0 && currentTaskExecutionsView != null)
            {
                UpdateReport();
                ctrlExportToExcel.IsEnabled = true;
                ctrlUpdateReport.IsEnabled = true;
            }
        }

        protected void UpdateReport()
        {
            if (ctrlTaskExecutions.ItemsSource == null)
            {
                ctrlTaskExecutions.ItemsSource = currentTaskExecutionsView;
            }
            Report r = CurrentReport;
            currentTaskExecutionsView.Filter = (r == null) ? null : r.Filter;
            if (r != null)
            {
                ctrlLastUpdatedAt.Text = DateTime.Now.ToShortTimeString();
                r.TaskExecutions = currentTaskExecutionsView;
                r.UpdateReport();
                if (r.TotalWorkingTime != null)
                {
                    ctrlWorkingTotal.Text = String.Format(TimeTemplate, Math.Floor(r.TotalWorkingTime.Value.TotalHours).ToString("00"), r.TotalWorkingTime.Value.Minutes.ToString("00"));
                }
                if (r.TotalRestingTime != null)
                {
                    ctrlRestingTotal.Text = String.Format(TimeTemplate, Math.Floor(r.TotalRestingTime.Value.TotalHours).ToString("00"), r.TotalRestingTime.Value.Minutes.ToString("00"));
                }
        }
    }

        protected void ExportToExcel()
        {
            Report r = CurrentReport;
            if (r != null)
            {
                string templatesPath = App.CurrentApp.CurrentConfig.ExcelExportTemplatesFolder;
                if (String.IsNullOrEmpty(templatesPath))
                {
                    templatesPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                }
                System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
                dialog.Filter = "Excel|*.xls";

                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && !String.IsNullOrEmpty(dialog.FileName))
                {
                    bool savedOk = true;
                    currentTaskExecutionsView.Filter = r.Filter;
                    r.TaskExecutions = currentTaskExecutionsView;
                    r.UpdateReport();

                    Excel.Application excelApp = null;
                    Excel.Workbook excelBook = null;

                    Excel.Workbooks excelBooks = null;
                    Excel.Sheets excelSheets = null;
                    Excel.Worksheet excelSheet = null;
                    Excel.Range cells = null;
                    try
                    {
                        excelApp = new Excel.Application();
                        excelApp.Visible = false;
                        excelApp.ShowStartupDialog = false;
                        excelApp.ShowWindowsInTaskbar = false;

                        excelBooks = excelApp.Workbooks;

                        excelBooks.Open(templatesPath + "\\template.xlt",
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value);

                        excelBook = excelBooks[1];

                        excelSheets = excelBook.Worksheets;
                        excelSheet = (Excel.Worksheet)excelSheets[1];
                        excelSheet.Name = "My Sheet!!blah";

                        cells = excelSheet.Cells;

                        // Dump Data
                        int titleRow, row, column;
                        Excel.Range cell;
                        double oldValue;
                        DateTime endTime;
                        User currentUser = App.CurrentApp.CurrentModel.CurrentUser;
                        cells[12, 5] = currentUser.Name;
                        cells[12, 17] = DateTime.Now.Month;
                        cells[51, 3] = DateTime.Now.ToShortDateString();

                        titleRow = 24;
                        row = 25;

                        foreach (Project p in App.CurrentApp.CurrentModel.CurrentUser.Projects)
                        {
                            cells[titleRow, 2] = p.Name;
                            foreach (TaskExecution t in currentTaskExecutionsView)
                            {
                                column = 2 + t.StartTime.Day - 1;
                                if (t.Task.IsWorkingTime && t.Task.ParentProject == p)
                                {
                                    oldValue = 0;
                                    cell = (Excel.Range)cells[row, column];
                                    if (cell != null && !String.IsNullOrEmpty(cell.Text.ToString()) && Double.TryParse(cell.Text.ToString(), out oldValue))
                                    {
                                    }
                                    if (t.EndTime == null)
                                    {
                                        endTime = DateTime.Now;
                                    }
                                    else
                                    {
                                        endTime = t.EndTime.Value;
                                    }
                                    cells[row, column] = oldValue + endTime.Subtract(t.StartTime).TotalHours;
                                    System.Runtime.InteropServices.Marshal.ReleaseComObject(cell);
                                    cell = null;
                                }
                            }
                            titleRow = titleRow + 3;
                            row = row + 3;
                        }

                        excelSheet.SaveAs(dialog.FileName,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value,
                            System.Reflection.Missing.Value);

                    }
                    catch (Exception ex)
                    {
                        savedOk = false;
                        App.CurrentApp.LogException(ex);
                        MessageBox.Show("There was an error saving the XLS file." + ex.Message);
                    }
                    finally
                    {
                        if (excelBook != null)
                        {
                            excelBook.Close(false, null, null);
                        }
                        if (excelApp != null)
                        {
                            excelBooks.Close();
                            excelApp.Quit();
                        }

                        if (cells != null)
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(cells);
                        if (excelSheets != null)
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheets);
                        if (excelSheet != null)
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet);
                        if (excelBooks != null)
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelBooks);
                        if (excelBook != null)
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelBook);
                        if (excelApp != null)
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);

                        cells = null;
                        excelSheets = null;
                        excelSheet = null;
                        excelBooks = null;
                        excelBook = null;
                        excelApp = null;
                        System.GC.Collect();
                    }

                    if (savedOk)
                    {
                        try
                        {
                            if (MessageBox.Show("Do you want to open the exported file now?", "Question", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                            {
                                System.Diagnostics.Process.Start(dialog.FileName);
                            }
                        }
                        catch (Exception ex)
                        {
                            App.CurrentApp.LogException(ex);
                            MessageBox.Show("There was a problem trying to open your just-generated report. Please, try to open it manually from " + dialog.FileName + ". " + ex.Message);
                        }
                    }
                }
                
            }
        }

    }
}